<script setup lang="ts">
import * as echarts from 'echarts'
// import useUserStore from '@/store/modules/user.ts'
// import { getTime } from '@/utils/time.ts'
// let userStore = useUserStore()

import { ref, onMounted, reactive } from 'vue'
import { getChartsData } from '@/api/screen/Year/index.ts'
// import { reqDataType } from '@/api/screen/Year/type.ts'
import moment from 'moment'
let charts = ref()
let zData = reactive<any>([])
let Result = ref<any>([])
let time = ref(moment().format('YYYY年MM月DD日'))
let yMonth = ref(moment().format('M'))
// xData
let yearData = ref<any>([])
for (let i = 1; i <= 12; i++) {
  if (yMonth.value >= i.toString()) {
    yearData.value.push(`${time.value.slice(0, 4)}年${i}月`)
  } else {
    yearData.value.push(`${Number(time.value.slice(0, 4)) - 1}年${i}月`)
  }
}
const selectCompany = ref()
const selectYChange = ref()
let option = {}
let echartsTitle = ref(`${time.value}近十二个月的下单总金额`)
const companyList = ref<any>([])
onMounted(async () => {
  await allData()
  echartsData()
})
// 获取所有数据
const allData = async () => {
  let res: any = await getChartsData('find', '', '')
  // console.log(res)
  if (res.data.e === 0) {
    res.data.d.forEach((item: any, index: number) => {
      Result.value = []
      companyList.value.push({
        label: item.name == null ? '其他' : item.name,
        value: item.id_enterprise == null ? '' : item.id_enterprise,
      })
      for (let i = 1; i <= 12; i++) {
        const monthData = item.details.find((month: any) => {
          return month.month === i.toString()
        })
        if (monthData) {
          res.data.d[index].details.forEach((dataItem: any) => {
            if (dataItem.month == i.toString()) {
              Result.value.push(dataItem.sum_pay)
            }
          })
        } else {
          Result.value.push('0')
        }
      }
      zData.push({
        name: item.name == null ? '其他' : item.name,
        data: Result.value,
      })
    })
  }
}

const echartsData = () => {
  echarts.dispose(charts.value)
  let myCharts = echarts.init(charts.value)
  // 计算总和
  const arrSum = (yData: any) => {
    const list = yData.map((v: any) => v.data)
    let sumList = ref<any>([])
    const xLen = list[0].length
    for (let i = 0; i < xLen; i++) {
      let sum = 0
      for (let j = 0; j < list.length; j++) {
        sum += parseFloat(list[j][i.toString()] || 0)
      }
      sumList.value.push(sum.toFixed(3))
    }
    return sumList.value
  }
  const xData = yearData.value
  const yData = zData
  let series1 = yData.map((item: any) => {
    return {
      name: item.name,
      data: item.data,
      type: 'bar',
      stack: 'fruit',
      emphasis: { focus: 'series' },
      animationDuration: 1500,
      animationEasing: 'cubicInOut',
      barWidth: 20,
      barGap: 1,
      itemStyle: {
        borderRadius: 2,
        borderWidth: 2,
        borderColor: 'transparent',
        borderJoin: 'round',
        borderType: 'solid',
      },
      label: {
        show: false,
        color: '#fafafa',
        fontSize: 12,
      },
    }
  })
  const series2 = {
    name: 'Total',
    color: '#a1a6b1',
    data: arrSum(yData),
    type: 'line',
    lineStyle: {
      // type: 'dashed',
      // 实线宽度,虚线宽度
      type: [8, 6],
      dashOffset: 0,
    },
    label: {
      show: true,
      color: 'inherit',
      fontSize: 12,
    },
  }
  option = {
    title: {
      show: true,
      text: echartsTitle.value,
      textStyle: {
        color: '#000',
        fontSize: 20,
      },
    },
    series: [...series1, series2],
    yAxis: [
      {
        type: 'value',
        axisLabel: {
          show: true,
          color: '#000',
        },
      },
    ],
    grid: {
      top: '20%',
      left: '2%',
      right: '3%',
      bottom: '0%',
      containLabel: true,
    },

    xAxis: {
      type: 'category',
      boundaryGap: true,
      data: xData,
      axisLabel: {
        show: true,
        color: '#000',
      },
      axisTick: { show: false },
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'line',
      },
      textStyle: {
        color: '#fafafa',
      },
      borderColor: 'transparent',
      backgroundColor: 'rgba(0, 0, 0, 0.5)',
      extraCssText: 'backdrop-filter: blur(6px);',
      order: 'seriesDesc',
    },
    legend: {
      show: true,
      right: 20,
      top: 30,
      icon: 'roundRect',
      itemHeight: 5,
      itemWidth: 10,
      itemGap: 40,
      textStyle: {
        color: '#000',
        fontSize: 16,
      },
      itemStyle: {
        borderColor: 'transparent',
        borderWidth: 12,
      },
    },
  }
  myCharts.setOption(option, true, true)
}

let tData = reactive<any>([])
// 获取带有年份的所有数据
const allDataAndYear = async (act: any, id: '', year: any) => {
  tData = []
  yearData.value = []
  let res: any = await getChartsData(act, id, year)
  if (res.data.e === 0) {
    res.data.d.forEach((item: any, index: number) => {
      Result.value = []
      for (let i = 1; i <= 12; i++) {
        const monthData = item.details.find((month: any) => {
          return month.month === i.toString()
        })
        if (monthData) {
          res.data.d[index].details.forEach((dataItem: any) => {
            if (dataItem.month == i.toString()) {
              Result.value.push(dataItem.sum_pay)
            }
          })
        } else {
          Result.value.push('0')
        }
      }
      tData.push({
        name: item.name == null ? '其他' : item.name,
        data: Result.value,
      })
    })
  }
  zData = tData
  for (let i = 1; i <= 12; i++) {
    yearData.value.push(`${selectYChange.value}年${i}月`)
  }
  echartsData()
}

const yOptions = ref<any>([])
const currentYear = Number(time.value.slice(0, 4))
const startYear = 2019
let years = Array.from(
  { length: currentYear - startYear + 1 },
  (_, index) => startYear + index,
)
years.reverse().forEach((item) => {
  yOptions.value.push({ value: item, label: item })
})
// 获取公司
const getCompany = async (act: any, id: '', year: any) => {
  tData = []
  let res: any = await getChartsData(act, id, year)
  if (res.data.e === 0) {
    Result.value = []
    for (let i = 1; i <= 12; i++) {
      const monthData = res.data.d.find((month: any) => {
        return month.month === i.toString()
      })
      if (monthData) {
        res.data.d.forEach((dataItem: any) => {
          if (dataItem.month == i.toString()) {
            Result.value.push(dataItem.sum_pay)
          }
        })
      } else {
        Result.value.push('0')
      }
    }
    let companyName = companyList.value.filter(
      (item: any) => item.value === selectCompany.value,
    )
    tData.push({ name: companyName[0].label, data: Result.value })
  }
  zData = tData

  if (selectYChange.value) {
    yearData.value = []
    for (let i = 1; i <= 12; i++) {
      yearData.value.push(`${selectYChange.value}年${i}月`)
    }
  }
  echartsData()
}
const selectYearChange = async () => {
  echartsTitle.value = selectYChange.value + '年的下单总额'
  if (!selectCompany.value) {
    await allDataAndYear('find', '', selectYChange.value)
  } else {
    await getCompany('search', selectCompany.value, selectYChange.value)
  }
}
const selectChange = async () => {
  await getCompany(
    'search',
    selectCompany.value,
    selectYChange.value == undefined ? '' : selectYChange.value,
  )
}
</script>

<template>
  <!--  <el-card>-->
  <!--    <div class="header">-->
  <!--      <img :src="userStore.avatar" alt="头像" />-->
  <!--      <div class="text">-->
  <!--        <h1>{{ getTime() }}好呀! {{ userStore.username }}</h1>-->
  <!--        <i>二木儿甄选运营平台</i>-->
  <!--      </div>-->
  <!--    </div>-->
  <!--  </el-card>-->
  <div class="operate">
    <el-select
      v-model="selectYChange"
      placeholder="选择年"
      size="large"
      style="width: 240px"
      @change="selectYearChange"
    >
      <el-option
        v-for="item in yOptions"
        :key="item.value"
        :label="item.label"
        :value="item.value"
      />
    </el-select>
    <el-select
      v-model="selectCompany"
      class="select"
      placeholder="选择公司"
      size="large"
      style="width: 240px"
      @change="selectChange"
    >
      <el-option
        v-for="item in companyList"
        :key="item.value"
        :label="item.label"
        :value="item.value"
      />
    </el-select>
  </div>
  <div class="charts" ref="charts"></div>
  <!--  <div class="bottom">-->
  <!--    <svg-icon name="welcome" width="600px" height="350px"></svg-icon>-->
  <!--  </div>-->
</template>

<style scoped lang="scss">
.header {
  display: flex;
  img {
    width: 150px;
    height: 150px;
    border-radius: 50%;
    margin-right: 10px;
  }
  .text {
    display: flex;
    flex-direction: column;
    justify-content: center;
    h1 {
      font-size: 32px;
      font-weight: 700;
    }
    i {
      font-size: 16px;
      color: #666;
      margin-top: 30px;
    }
  }
}
.operate {
  margin-bottom: 30px;
  .select {
    margin-left: 20px;
  }
}
.charts {
  margin: 10px auto 0;
  width: 100%;
  height: 600px;
  //background-color: #0c2134;
}
.bottom {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 150px;
}
</style>
